/*
 * @Author: silence
 * @Date: 2023-07-04 17:02:12
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2024-04-15 11:40:12
 * @Description: 电站详情——发电量
 */
import 'package:ems_neutral_app/api/request/PowerStationRequest.dart';
import 'package:ems_neutral_app/common/interfaceInstance/FutureBuilderInterfaceInstance.dart';
import 'package:ems_neutral_app/pages/Mine/Language/SilLocalizations/SilLocalizations.dart';
import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:sil_base_widget_package/sil_base_widget_package.dart';
import 'package:sil_utils_package/sil_utils_package.dart';
import 'package:sil_utils_package/tools/SilTools.dart';
import 'package:syncfusion_flutter_charts/charts.dart';

import '../../../api/R.dart';
import '../../../bloc/userbloc/user_bloc.dart';
import '../../../utils/color/ColorUtils.dart';

class PsDetailEnergyChartView extends StatefulWidget {
  const PsDetailEnergyChartView({super.key});

  @override
  State<PsDetailEnergyChartView> createState() =>
      _PsDetailEnergyChartViewState();
}

class _PsDetailEnergyChartViewState extends State<PsDetailEnergyChartView>
    with FutureBuilderInterfaceInstance {
  TooltipBehavior _tooltipBehavior = TooltipBehavior(
      enable: true, shared: true, activationMode: ActivationMode.singleTap);

  dynamic _future;

  /// 用电量
  List<_SalesData> _ydlData = [];

  /// 发电量
  List<_SalesData> _fdlData = [];

  int? _year, _month, _day;
  late RefreshController _refreshController;
  late ZoomPanBehavior _zoomPanBehavior;

  @override
  void initState() {
    super.initState();

    /// 默认显示日
    _day = DateTime.now().day; //获取当前日(1-31)
    _future = getData();
    _zoomPanBehavior = ZoomPanBehavior(
        enablePanning: true,
        zoomMode: ZoomMode.x,
        enableDoubleTapZooming: true);
    _refreshController = RefreshController(initialRefresh: false);
  }

  getData() async {
    String? powerRecordId = UserBlocTool.userEntity?.powerRecordId;
    if (SilTools.stringIsEmpty(powerRecordId)) {
      return;
    }

    R r = await api_power_station_plant_chart(
        deviceId: powerRecordId!, year: _year, month: _month, day: _day);
    return r.data;
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 20.w),
      child: contentView(),
    );
  }

  contentView() {
    return Column(
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        /// 标题
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Expanded(flex: 1, child: leftTitleView()),
            yearMonthDayBtns()
          ],
        ),

        /// PV1电压/PV2电压/输出电流
        chartFutureView(),
      ],
    );
  }

  /// 发电量/用电量对比
  leftTitleView() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        SilImage(
          'imgs/home/home_xt.png',
          height: 25.w,
          width: 25.w,
          margin: EdgeInsets.only(right: 2.w),
        ),
        Expanded(
            child: SilText(
          LangOf(context)?.dz_zzw?.g_c,
          fontSize: 16.sp,
          maxLines: 0,
          color: ColorUtils.color_font_main,
        ))
      ],
    );
  }

  /// 年月日
  yearMonthDayBtns() {
    return Container(
      margin: EdgeInsets.only(left: 10.w),
      alignment: Alignment.centerRight,
      child: Row(
        children: [
          SilButton(
            title: LangOf(context)?.dz_zzw?.year,
            fontSize: 13.sp,
            titleColor: (_year == null)
                ? ColorUtils.color_font_main
                : ColorUtils.color_theme,
            onTapFunc: () {
              _year = DateTime.now().year;
              _month = null;
              _day = null;
              setState(() {
                _future = getData();
              });
            },
          ),
          Container(
            width: 1.w,
            height: 15.w,
            color: ColorUtils.color_font_main,
            margin: EdgeInsets.symmetric(horizontal: 6.w),
          ),
          SilButton(
              title: LangOf(context)?.dz_zzw?.month,
              titleColor: (_month == null)
                  ? ColorUtils.color_font_main
                  : ColorUtils.color_theme,
              fontSize: 13.sp,
              onTapFunc: () {
                _year = null;
                _month = DateTime.now().month; //获取当前月份(1-12)
                _day = null;
                setState(() {
                  _future = getData();
                });
              }),
          Container(
            width: 1.w,
            height: 15.w,
            color: ColorUtils.color_font_main,
            margin: EdgeInsets.symmetric(horizontal: 6.w),
          ),
          SilButton(
            title: LangOf(context)?.dz_zzw?.day,
            fontSize: 13.sp,
            titleColor: (_day == null)
                ? ColorUtils.color_font_main
                : ColorUtils.color_theme,
            onTapFunc: () {
              _year = null;
              _month = null;
              _day = DateTime.now().day; //获取当前日(1-31)
              setState(() {
                _future = getData();
              });
            },
          ),
        ],
      ),
    );
  }

  chartFutureView() {
    return Container(
        // width: 800.w,
        height: 320.w,
        child: SilFutureBuilderWidget(
            refreshController: _refreshController,
            future: _future,
            mainWidget: (data) {
              handlerData(data);
              return chartWidget();
            },
            reloadFunc: () {
              _future = getData();
              setState(() {});
            },
            interface: this));
  }

  handlerData(List data) {
    if (SilTools.listIsEmpty(data)) {
      return;
    }
    _ydlData = [];
    _fdlData = [];

    for (var i = 0; i < data.length; i++) {
      Map tempMap = data[i];
      // 'time': time,
      // 'fadian': tempMap['fadian'],
      // 'yongdian': tempMap['yongdian']
      /// 用电量
      _ydlData.add(
        _SalesData(tempMap['time'], (tempMap['yongdian'])),
      );

      /// 发电量
      _fdlData.add(
        _SalesData(tempMap['time'], (tempMap['fadian'])),
      );
    }
  }

  chartWidget() {
    return SfCartesianChart(
        key: GlobalKey<State>(),
        enableAxisAnimation: false,
        backgroundColor: Colors.black,
        primaryXAxis: CategoryAxis(
          borderWidth: 0,
          borderColor: Colors.transparent,
          autoScrollingDelta: 6,
          autoScrollingMode: AutoScrollingMode.start,
          interval: 1,

          /// 不显示主轴上的网格线
          majorGridLines: MajorGridLines(
              width: 0.5, color: ColorUtils.color_subtitle), // 网格线
          majorTickLines: MajorTickLines(width: 0), // 标记线
          axisLine: AxisLine(width: 1, color: ColorUtils.color_font_main), // 轴线
        ),
        primaryYAxis: NumericAxis(
          /// 不显示主轴上的网格线
          majorGridLines: MajorGridLines(
              width: 0.5, color: ColorUtils.color_subtitle), // 网格线
          majorTickLines: MajorTickLines(width: 0), // 标记线
          axisLine: AxisLine(width: 1, color: ColorUtils.color_font_main), // 轴线
        ),
        // 标题
        title: ChartTitle(
            text: '（kWh）',
            alignment: ChartAlignment.near,
            textStyle: TextStyle(fontSize: 14, shadows: List.empty())),
        // 图示标志
        legend: Legend(
            isVisible: true,
            alignment: ChartAlignment.center,
            position: LegendPosition.bottom,
            textStyle: TextStyle(color: ColorUtils.color_subtitle)),
        // 可点击
        tooltipBehavior: _tooltipBehavior,
        // 可滑动
        zoomPanBehavior: _zoomPanBehavior,
        plotAreaBorderWidth: 0,
        series: eries());
  }

  List<ChartSeries<_SalesData, String>> eries() {
    List<ChartSeries<_SalesData, String>> list =
        <ChartSeries<_SalesData, String>>[
      /// 用电量
      SplineAreaSeries<_SalesData, String>(
        splineType: SplineType.monotonic, // 解决，当区域图表的两条线的值都是0时，绘制的线可能会呈现抛物线的形状
        dataSource: _ydlData,
        name: LangOf(context)?.dz_zzw?.gc,
        xValueMapper: (_SalesData sales, _) => sales.date,
        yValueMapper: (_SalesData sales, _) => sales.sales,

        /// 修饰数据点，显示原点
        markerSettings: MarkerSettings(isVisible: true, width: 5, height: 5),
        color: ColorUtils.color_chart_line_06,
        borderColor: ColorUtils.color_chart_line,
        borderWidth: 2,
        animationDuration: 0,
      ),

      /// 发电量
      SplineAreaSeries<_SalesData, String>(
        splineType: SplineType.monotonic, // 解决，当区域图表的两条线的值都是0时，绘制的线可能会呈现抛物线的形状
        dataSource: _fdlData,
        name: LangOf(context)?.dz_zzw?.ec,
        xValueMapper: (_SalesData sales, _) => sales.date,
        yValueMapper: (_SalesData sales, _) => sales.sales,

        /// 修饰数据点，显示原点
        markerSettings: MarkerSettings(isVisible: true, width: 5, height: 5),
        color: ColorUtils.color_theme_06,
        borderColor: ColorUtils.color_theme,
        borderWidth: 2,
        animationDuration: 0,
      ),
    ];

    return list;
  }
}

class _SalesData {
  _SalesData([this.date, this.sales]);

  final String? date;
  final double? sales;
}
